import cPickle as pickle
import os
import os.path as osp
import shutil
import sys

from optparse import OptionParser

import tables

def move():
    op = OptionParser(usage="Usage: mp3same move [opts] dupes_dir match.pkl")
    op.add_option('-o', '--output', dest='output', default="move.h5",
                  help='Write undo file to FILE', metavar='FILE')

    (opts,args) = op.parse_args()

    if len(args) < 4:
        sys.stderr.write("`mp3same.py move' requires three arguments.\n")
        sys.stderr.write("See `mp3same.py move -h' for more.\n")
        sys.stderr.flush()
        return 1

    dupesdir = args[1]
    
    if not osp.exists(dupesdir):
        try:
            os.mkdir(osp.abspath(dupesdir)) 
        except os.OSError,e:
            sys.stderr.write("Error creating output path `" + dupesdir + "'\n")
            sys.stderr.write("Aborting...\n")
            sys.stderr.flush()
            return 2

    elif not osp.isdir(dupesdir):
        sys.stderr.write("`" + dupesdir + "' exists and is not a directory.\n")
        sys.stderr.write("See `mp3same.py move -h' for more.\n")
        sys.stderr.flush()
        return 2

#    fpgen = tables.openFile(args[2], 'r')
    fpmatch = open(args[2], 'r')

    matches = pickle.load(fpmatch)

    for matchdict in matches:
        similar_songs = dict()

        find_all_related(similar_songs, 
                         fpmatch.root.mnt[index], 
                         fpmatch.root.mnt,
                         opts.rcut)
      
        print similar_songs
        continue
        
        print count, 'of', total

 #       for 
        arrname1_rows = fpgen.root.hdrnt.readWhere("arrname == '" + mrow['arrname1'] + "'") 
        grow2 = fpgen.root.hdrnt.readWhere("arrname == '" + mrow['arrname2'] + "'") 
    
        if len(grow1) == 0:
            sys.stderr.write("Row with md5 `" + mrow['arrname1'][3:] + "' not found.\n")
            sys.stderr.write("Skipping...\n")
            sys.stderr.flush()
            continue

        if len(grow2) == 0:
            sys.stderr.write("Row with md5 `" + mrow['arrname2'][3:] + "' not found.\n")
            sys.stderr.write("Skipping...\n")
            sys.stderr.flush()
            continue

        
        if grow1['bitrate'] < grow2['bitrate']:
            row_to_move = grow1[0]
        else:
            row_to_move = grow2[0]

        if row_to_move in movelist:
            resolve_collision(row_to_move, movelist)
        else:
            movelist[row_to_move['fname']] = row_to_move['bitrate']

        count += 1 

    undo_list = list()

    for path in movelist:
        try:
            shutil.move(path, dupesdir)
        except IOError,e:
            
            sys.stderr.write(str(e) + "\n")
            sys.stderr.write("Skipping...\n")
            sys.stderr.flush()
            continue 

        undo_list.append((path, dupesdir))

    ofp = open(opts.output, 'wb')
    pickle.dump(undo_list, ofp)
    ofp.close()
    
    return 0
